<template>
  <div class="media-analysis-platform">
    <!-- 页面标题 -->
    <div class="platform-header">
      <h1 class="platform-title">媒体数据分析平台</h1>
      <p class="platform-subtitle">精准采集 · 智能分析 · 数据洞察</p>
    </div>

    <!-- 功能区域容器 -->
    <div class="platform-content">
      <!-- 左侧功能区 -->
      <div class="left-panel">
        <!-- 精准采集组件 -->
        <PreciseCollection @collection-success="handleCollectionSuccess" />
        
        <!-- 批量搜索组件 -->
        <BatchSearch @search-success="handleSearchSuccess" />
      </div>

      <!-- 右侧作品展示区域 -->
      <div class="right-panel">
        <!-- 作品展示组件 -->
        <WorkDisplay 
          ref="workDisplayRef"
          :works="worksList" 
          :total="totalWorks"
          :loading="worksLoading"
          @work-click="handleWorkClick"
          @work-analysis="handleWorkAnalysis"
          @page-change="handlePageChange"
        />
        
        <!-- 内容分析弹窗 -->
        <ContentAnalysis
          v-model="showAnalysisDialog"
          :work-data="currentAnalysisWork"
          @export="handleAnalysisExport"
        />
      </div>
    </div>

    <!-- 内容分析弹窗 -->
    <el-dialog
      v-model="analysisDialogVisible"
      title="内容分析"
      width="80%"
      class="analysis-dialog"
    >
      <div class="analysis-content" v-if="selectedWork">
        <!-- 作品基本信息 -->
        <div class="analysis-basic">
          <div class="basic-left">
            <img :src="selectedWork.cover" class="analysis-cover" />
          </div>
          <div class="basic-right">
            <h3 class="analysis-title">{{ selectedWork.title }}</h3>
            <div class="analysis-author">
              <img :src="selectedWork.authorAvatar" class="analysis-avatar" />
              <span class="analysis-author-name">{{ selectedWork.authorName }}</span>
            </div>
            <div class="analysis-stats">
              <div class="analysis-stat">
                <span class="stat-label">点赞数</span>
                <span class="stat-number">{{ formatNumber(selectedWork.likes) }}</span>
              </div>
              <div class="analysis-stat">
                <span class="stat-label">评论数</span>
                <span class="stat-number">{{ formatNumber(selectedWork.comments) }}</span>
              </div>
              <div class="analysis-stat">
                <span class="stat-label">分享数</span>
                <span class="stat-number">{{ formatNumber(selectedWork.shares) }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 数据分析图表 -->
        <div class="analysis-charts">
          <div class="chart-item">
            <h4 class="chart-title">互动趋势分析</h4>
            <div class="chart-container" ref="trendChartRef"></div>
          </div>
          <div class="chart-item">
            <h4 class="chart-title">用户画像分析</h4>
            <div class="chart-container" ref="userChartRef"></div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
/** @name 媒体数据分析平台主页面 */

// 导入组件
import PreciseCollection from '@/components/Media/PreciseCollection.vue'
import BatchSearch from '@/components/Media/BatchSearch.vue'
import WorkDisplay from '@/components/Media/WorkDisplay.vue'
import ContentAnalysis from '@/components/Media/ContentAnalysis.vue'

// 导入状态管理
import { useMediaStore } from '@/stores/modules/media'
import { storeToRefs } from 'pinia'

// 使用媒体store
const mediaStore = useMediaStore()
const { works, currentWork, collectionProgress, searchProgress } = storeToRefs(mediaStore)
const { setWorks, setCurrentWork, addWorks } = mediaStore

// 作品数据
const worksList = ref([])
const totalWorks = ref(0)
const worksLoading = ref(false)

// 分析弹窗
const analysisDialogVisible = ref(false)
const selectedWork = ref(null)
const showAnalysisDialog = ref(false)
const currentAnalysisWork = ref(null)

// 图表引用
const trendChartRef = ref(null)
const userChartRef = ref(null)

// WorkDisplay 组件引用
const workDisplayRef = useTemplateRef("workDisplayRef")

/** @name 格式化数字 */
function formatNumber(num) {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  }
  return num.toString()
}

/** @name 处理精准采集成功 */
function handleCollectionSuccess(data) {
  // 开始采集进度
  mediaStore.startCollection(data.quantity || 1)
  
  // 模拟采集过程
  setTimeout(() => {
    worksList.value = data.works || []
    totalWorks.value = data.total || 0
    addWorks(data.works || [])
    
    // 添加到采集历史
    mediaStore.addCollectionHistory({
      url: data.url,
      type: data.type,
      quantity: data.quantity,
      includeComments: data.includeComments,
      includeUserInfo: data.includeUserInfo
    })
    
    // 完成采集
    mediaStore.completeCollection()
    
    workDisplayRef.value.handleRefresh()
    
    ElMessage.success('采集成功')
  }, 2000)
}

/** @name 处理批量搜索成功 */
function handleSearchSuccess(data) {
  // 开始搜索进度
  mediaStore.startSearch(data.quantity || 20)
  
  // 模拟搜索过程
  setTimeout(() => {
    worksList.value = data.works || []
    totalWorks.value = data.total || 0
    addWorks(data.works || [])
    
    // 添加到搜索历史
    mediaStore.addSearchHistory({
      keywords: data.keywords,
      filters: data.filters,
      resultCount: (data.works || []).length
    })
    
    // 完成搜索
    mediaStore.completeSearch()
    ElMessage.success('搜索完成')
  }, 3000)
}

/** @name 处理作品点击 */
function handleWorkClick(work) {
  selectedWork.value = work
  analysisDialogVisible.value = true
}

/** @name 处理作品分析 */
function handleWorkAnalysis(work) {
  setCurrentWork(work)
  currentAnalysisWork.value = work
  showAnalysisDialog.value = true
}

/** @name 处理分析报告导出 */
function handleAnalysisExport(workData) {
  console.log('导出分析报告:', workData)
  // 这里可以实现报告导出功能
}

/** @name 处理分页变化 */
function handlePageChange(pageData) {
  // 这里可以根据分页信息重新加载数据
  console.log('分页变化:', pageData)
}

/** @name 加载初始数据 */
function loadInitialData() {
  worksLoading.value = true
  
  // 模拟作品数据
  const mockWorks = []
  for (let i = 1; i <= 12; i++) {
    mockWorks.push({
      id: i,
      title: `精彩作品标题 ${i} - 这是一个很有趣的内容`,
      cover: `https://picsum.photos/300/400?random=${i}`,
      type: i % 3 === 0 ? 'image' : 'video',
      duration: i % 3 === 0 ? null : `${Math.floor(Math.random() * 3) + 1}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
      authorName: `用户${i}`,
      authorAvatar: `https://picsum.photos/50/50?random=${i + 100}`,
      likes: Math.floor(Math.random() * 1000000) + 10000,
      comments: Math.floor(Math.random() * 50000) + 1000,
      shares: Math.floor(Math.random() * 10000) + 500,
      publishTime: `2024-01-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`
    })
  }
  
  setTimeout(() => {
    worksList.value = mockWorks
    totalWorks.value = 156
    worksLoading.value = false
  }, 1000)
}

// 组件挂载时加载数据
onMounted(() => {
  loadInitialData()
})
</script>

<style lang="scss" scoped>
.media-analysis-platform {
  min-height: 100vh;
  background: $qf-color-bg1;
  padding: 24px;
  
  .platform-header {
    text-align: center;
    margin-bottom: 32px;
    
    .platform-title {
      font-size: 32px;
      font-weight: bold;
      color: $qf-text-color-primary;
      margin: 0 0 8px 0;
      background: linear-gradient(90deg, $qf-primary 0%, $qf-primary2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    
    .platform-subtitle {
      font-size: 16px;
      color: $qf-text-color-secondary;
      margin: 0;
    }
  }
  
  .platform-content {
    display: flex;
    gap: 24px;
    max-width: 1400px;
    margin: 0 auto;
  }
  
  .left-panel {
    width: 400px;
    flex-shrink: 0;
  }
  
  .right-panel {
    flex: 1;
  }
  
  .section-header {
    margin-bottom: 16px;
    
    .section-title {
      font-size: 18px;
      font-weight: 600;
      color: $qf-text-color-primary;
      margin: 0 0 4px 0;
    }
    
    .section-desc {
      font-size: 14px;
      color: $qf-text-color-secondary;
    }
  }
  
  // 精准采集区域
  .collection-section {
    background: $qf-color-bg2;
    border: 1px solid $qf-border-color;
    border-radius: $qf-border-radius-lg;
    padding: 20px;
    margin-bottom: 24px;
    
    .collection-form {
      display: flex;
      flex-direction: column;
      gap: 12px;
      
      .collection-input {
        :deep(.el-input-group__prepend) {
          background: $qf-color-bg3;
          border-color: $qf-border-color;
          color: $qf-text-color-secondary;
        }
      }
      
      .collection-btn {
        align-self: flex-start;
      }
    }
  }
  
  // 批量搜索区域
  .search-section {
    background: $qf-color-bg2;
    border: 1px solid $qf-border-color;
    border-radius: $qf-border-radius-lg;
    padding: 20px;
    
    .search-form {
      display: flex;
      flex-direction: column;
      gap: 16px;
      
      .search-row {
        .search-input {
          :deep(.el-input-group__prepend) {
            background: $qf-color-bg3;
            border-color: $qf-border-color;
            color: $qf-text-color-secondary;
          }
        }
      }
      
      .filter-row {
        display: flex;
        flex-direction: column;
        gap: 12px;
        
        .filter-item {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .filter-label {
            font-size: 14px;
            color: $qf-text-color-secondary;
            width: 60px;
            flex-shrink: 0;
          }
          
          .el-select {
            flex: 1;
          }
        }
      }
      
      .search-btn {
        align-self: flex-start;
      }
    }
  }
  
  // 作品展示区域
  .works-section {
    background: $qf-color-bg2;
    border: 1px solid $qf-border-color;
    border-radius: $qf-border-radius-lg;
    padding: 20px;
    
    .works-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 16px;
      margin-bottom: 24px;
      min-height: 400px;
      
      .work-card {
        background: $qf-color-bg3;
        border: 1px solid $qf-border-color;
        border-radius: $qf-border-radius-lg;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: $qf-primary;
          transform: translateY(-2px);
          box-shadow: 0 8px 24px rgba(151, 164, 255, 0.15);
        }
        
        .work-preview {
          position: relative;
          
          .work-cover {
            width: 100%;
            height: 180px;
            object-fit: cover;
          }
          
          .work-type-badge {
            position: absolute;
            top: 8px;
            left: 8px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 2px 8px;
            border-radius: $qf-border-radius-sm;
            font-size: 12px;
          }
          
          .work-duration {
            position: absolute;
            bottom: 8px;
            right: 8px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 2px 6px;
            border-radius: $qf-border-radius-sm;
            font-size: 12px;
          }
        }
        
        .work-info {
          padding: 12px;
          
          .work-title {
            font-size: 14px;
            font-weight: 500;
            color: $qf-text-color-primary;
            margin: 0 0 8px 0;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
          
          .work-author {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-bottom: 8px;
            
            .author-avatar {
              width: 20px;
              height: 20px;
              border-radius: 50%;
            }
            
            .author-name {
              font-size: 12px;
              color: $qf-text-color-secondary;
            }
          }
          
          .work-stats {
            display: flex;
            gap: 12px;
            margin-bottom: 8px;
            
            .stat-item {
              display: flex;
              align-items: center;
              gap: 4px;
              
              .stat-icon {
                font-size: 14px;
                color: $qf-text-color-secondary;
              }
              
              .stat-value {
                font-size: 12px;
                color: $qf-text-color-secondary;
              }
            }
          }
          
          .work-time {
            font-size: 12px;
            color: $qf-text-color-disabled;
          }
        }
      }
    }
    
    .pagination-wrapper {
      display: flex;
      justify-content: center;
    }
  }
}

// 分析弹窗样式
:deep(.analysis-dialog) {
  .el-dialog {
    background: $qf-color-bg2;
    border: 1px solid $qf-border-color;
  }
  
  .el-dialog__header {
    border-bottom: 1px solid $qf-border-color;
    
    .el-dialog__title {
      color: $qf-text-color-primary;
    }
  }
  
  .el-dialog__body {
    padding: 24px;
  }
}

.analysis-content {
  .analysis-basic {
    display: flex;
    gap: 20px;
    margin-bottom: 24px;
    
    .basic-left {
      .analysis-cover {
        width: 200px;
        height: 150px;
        object-fit: cover;
        border-radius: $qf-border-radius-lg;
      }
    }
    
    .basic-right {
      flex: 1;
      
      .analysis-title {
        font-size: 20px;
        font-weight: 600;
        color: $qf-text-color-primary;
        margin: 0 0 12px 0;
      }
      
      .analysis-author {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 16px;
        
        .analysis-avatar {
          width: 32px;
          height: 32px;
          border-radius: 50%;
        }
        
        .analysis-author-name {
          font-size: 16px;
          color: $qf-text-color-secondary;
        }
      }
      
      .analysis-stats {
        display: flex;
        gap: 24px;
        
        .analysis-stat {
          text-align: center;
          
          .stat-label {
            display: block;
            font-size: 14px;
            color: $qf-text-color-secondary;
            margin-bottom: 4px;
          }
          
          .stat-number {
            display: block;
            font-size: 18px;
            font-weight: 600;
            color: $qf-primary;
          }
        }
      }
    }
  }
  
  .analysis-charts {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    
    .chart-item {
      .chart-title {
        font-size: 16px;
        font-weight: 500;
        color: $qf-text-color-primary;
        margin: 0 0 12px 0;
      }
      
      .chart-container {
        height: 300px;
        background: $qf-color-bg3;
        border: 1px solid $qf-border-color;
        border-radius: $qf-border-radius-lg;
        display: flex;
        align-items: center;
        justify-content: center;
        color: $qf-text-color-secondary;
      }
    }
  }
}
</style>